import { contextBridge, ipcRenderer } from 'electron'

// 向渲染进程暴露IPC方法
contextBridge.exposeInMainWorld('electronAPI', {
  // Chrome窗口相关
  getChromeWindows: () => ipcRenderer.invoke('get-chrome-windows'),
  getRunningChromeWindows: () => ipcRenderer.invoke('get-running-chrome-windows'),
  closeChromeWindow: (windowId: number) => ipcRenderer.invoke('close-chrome-window', windowId),
  closeRunningChromeWindow: (windowId: number, pid?: number) => ipcRenderer.invoke('close-running-chrome-window', windowId, pid),
  launchChromeProfile: (windowId: number) => ipcRenderer.invoke('launch-chrome-profile', windowId),
  launchChrome: (options: { userDataDir: string, port?: number }) => ipcRenderer.invoke('launch-chrome', options),

  // 屏幕相关
  getScreens: () => ipcRenderer.invoke('get-screens'),

  // 窗口排列相关
  arrangeWindows: (params: any) => ipcRenderer.invoke('arrange-windows', params),
  
  // 任务队列相关
  addLaunchTask: (args: { userDataDir: string, port?: number, profileNumber?: number, shortcutPath?: string }) => ipcRenderer.invoke('add-launch-task', args),
  addCloseTask: (args: { windowId: number, pid?: number }) => ipcRenderer.invoke('add-close-task', args),
  addArrangeTask: (args: { type: string, windowIds: number[], screen: any, direction?: string, margin?: number, params?: any }) => ipcRenderer.invoke('add-arrange-task', args),
  getTaskStatus: (taskId: string) => ipcRenderer.invoke('get-task-status', taskId),
  getAllTasks: () => ipcRenderer.invoke('get-all-tasks'),

  // 同步控制相关
  startSync: (windowIds: number[]) => ipcRenderer.invoke('start-sync', windowIds),
  stopSync: () => ipcRenderer.invoke('stop-sync'),

  // 文件系统相关
  createShortcut: (options: { target: string, args: string, name: string, icon?: string }) =>
    ipcRenderer.invoke('create-shortcut', options),
  selectChromeExecutable: () => ipcRenderer.invoke('select-chrome-executable'),
  selectDirectory: () => ipcRenderer.invoke('select-directory'),
  // 环境创建相关
  createChromeEnvironment: (config: any) => ipcRenderer.invoke('create-chrome-environment', config),

  // 系统相关
  checkAdminPermission: () => ipcRenderer.invoke('check-admin-permission'),
  restartAsAdmin: () => ipcRenderer.invoke('restart-as-admin'),
  quitApp: () => ipcRenderer.invoke('quit-app'),

  // 设置相关
  getSettings: () => ipcRenderer.invoke('get-settings'),
  saveSettings: (settings: any) => ipcRenderer.invoke('save-settings', settings),

  // 路径相关
  getDefaultPaths: () => ipcRenderer.invoke('get-default-paths')
})

// 监听主进程发送的事件
contextBridge.exposeInMainWorld('electronEvents', {
  onSyncStatusChange: (callback: (status: boolean) => void) => {
    ipcRenderer.on('sync-status-change', (event, status) => callback(status))
    return () => ipcRenderer.removeAllListeners('sync-status-change')
  },

  onWindowCreated: (callback: (windowInfo: any) => void) => {
    ipcRenderer.on('window-created', (event, windowInfo) => callback(windowInfo))
    return () => ipcRenderer.removeAllListeners('window-created')
  }
})